package com.example.lizh.mvp_example.model.impl;

import com.example.lizh.mvp_example.model.LoginModel;
import com.example.lizh.mvp_example.retrofit.model.bean.UserBean;
import com.example.lizh.mvp_example.retrofit.model.service.UserService;
import com.example.lizh.mvp_example.rxBus.RxBus;
import com.example.lizh.mvp_example.rxBus.event.LoginStoreChangeEvent;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lizh on 2017/8/17.
 */

public class LoginModelImpl implements LoginModel {
    @Override
    public void login(String name, String password) {
        Retrofit retrofit =new Retrofit.Builder()
                .baseUrl("http://api.0102003.com/XiaoququApi/public/")
                // 使用 Gson 数据转换器(返回实体类是 JSON Bean 时使用,注意使用前需 Compile 对应的转换器,默认转换为 OkHttp 的 ResponseBody 类型,否则返回实体类与转换器类型不一致会报错)
                .addConverterFactory(GsonConverterFactory.create())
                // 使用 RxJava2 作为回调适配器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .createWithScheduler(Schedulers.io()) 方法可设置默认在io线程
                .build();

        retrofit.create(UserService.class)
                .login(name, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<UserBean>() {
                    @Override
                    public void accept(@NonNull UserBean userBean) throws Exception {
                        if (userBean.getCode() == 200) { // 登录成功
                            RxBus.getInstance().send(new LoginStoreChangeEvent("登录成功"));
                        }  else { // 登录失败
                            RxBus.getInstance().send(new LoginStoreChangeEvent("登录失败"));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        // 登录请求异常
                        RxBus.getInstance().send(new LoginStoreChangeEvent("登录请求异常"));
                    }
                });
    }
}
